<script lang="ts" setup>
import type { FieldRule, FormInstance } from '@arco-design/web-vue'
// import NewIp from '../../components/NewIp.vue'
// import GetIP from '../../components/GetIP.vue'
import { Message } from '@arco-design/web-vue'
import {
  getCdnGroupListApi,
  getNodeDetailApi,
  updateCdnNodeApi,
} from '@/apis/modules/cdn.ts'
import GetIp from '../../components/GetIp.vue'

const loading = ref(false)
interface FormDataType {
  id: string
  name: string
  group_id: string
  cascade_level: number
  cascade_ip: string
  group_type?: number
  report_ips: string[]
  ips: Array<{ ip: string }>
  cascade_port: number
  enable_resolve: boolean
}
const route = useRoute()
// const { visible, open } = usePopup()
const nodeId = computed(() => route.params.id as string)
const formState = reactive<FormDataType>({
  id: '',
  name: '',
  group_id: '',
  group_type: 1,
  cascade_level: 1,
  cascade_ip: '',
  ips: [],
  report_ips: [],
  cascade_port: 1,
  enable_resolve: false,
})
const formRef = ref<FormInstance>()
const ipOptions = ref<LabelValue[]>([])
// const { groupOptions } = useGroupArea('region')
const rules = computed<Record<string, FieldRule>>(() => ({
  name: {
    required: true,
    validator(value, callback) {
      if (!value) {
        return callback('请输入节点名称')
      } else if (value.length < 4 || value.length > 32) {
        return callback('节点名称长度为4-32个字符')
      }
      callback()
    },
  },
  group_id: { required: true, message: '请选择节点集群' },
  cascade_level: { required: true, message: '请选择节点层级' },
  cascade_port: { required: true, message: '请输入级联端口' },
}))

const groupOptions = ref<LabelValue[]>([])
// 获取节点分组
async function getClusterList() {
  const res = await getCdnGroupListApi({ limit: 0 })
  const list = res.list ?? []

  groupOptions.value = list
    .map(item => ({ label: item.name!, value: item.id!, type: item.type }))
    .filter(Boolean)
}
const nodeIpRules: FieldRule = {
  required: true,
  validator: (value, callback) => {
    if (!value) {
      return callback('IP不能为空')
    }
    if (!regexpMap.ipv4.test(value)) {
      return callback('IP格式不正确')
    }
    callback()
  },
}
const tableColumn = buildColumns([
  {
    title: '节点 IP',
    slotName: 'ip',
  },
  {
    title: '操作',
    slotName: 'action',
    cellClass: 'actions-cell',
    width: 140,
  },
])
function handleValidateIp() {
  formState.ips.forEach((_item, idx) => {
    formRef.value?.validateField(`ips[${idx}].ip`)
  })
}
function handleTableCommand(command: string, index?: number) {
  const map: Record<string, any> = {
    add: () => {
      formState.ips.push({
        ip: '',
      })
    },
    delete: () => {
      // formRef.value?.resetFields(`ips[${index}].ip`)
      formState.ips!.splice(index!, 1)
    },
    set_main: () => {
      const mainIp = formState.ips[index!]
      // formRef.value?.validateField(`ips[${index}].ip`)
      if (!regexpMap.ipv4.test(mainIp.ip) || !mainIp.ip) {
        return ''
      } else {
        formState.ips.splice(index!, 1)
        formState.ips.unshift(mainIp)
      }
    },
  }
  map[command] && map[command]()
}

const nodeName = ref('')
function getNodeInfo() {
  // 获取节点信息
  getNodeDetailApi({ id: nodeId.value }).then((res) => {
    const node = res.node!
    formState.group_id = node.group.id!
    formState.group_type = node.group.type!
    formState.name = node.name!
    formState.cascade_level = node.cascade_level!
    formState.ips
      = node.ips?.map(item => ({ ip: item ?? '' })).filter(Boolean) ?? []
    ipOptions.value
      = node.ips?.map(item => ({ label: item ?? '', value: item ?? '' })) ?? []
    ipOptions.value.unshift({ label: '使用主 IP', value: '' })
    formState.cascade_ip = node.cascade_ip ?? ''
    formState.cascade_port = Number(node.cascade_port ?? 0)
    formState.report_ips = node.report_ips ?? []
    formState.enable_resolve = node.enable_resolve ?? false
    nodeName.value = node.name
  })
}

async function handleSave() {
  const error = await formRef.value?.validate()
  if (error)
    return
  const ips = formState.ips.map(item => item.ip).filter(Boolean)
  let data: any = {
    name: formState.name,
    group_id: formState.group_id,
    cascade_level: formState.cascade_level,
    ips,
    id: nodeId.value,
    enable_resolve: formState.enable_resolve,
  }
  if (formState.cascade_level === 2) {
    data = {
      ...data,
      cascade_port: formState.cascade_port,
      cascade_ip: formState.cascade_ip,
    }
  }
  let checkPass = true
  const report_ips = formState.report_ips ?? []
  for (let i = 0; i < ips.length; i++) {
    const index = report_ips.findIndex(item => item === ips[i])
    if (index < 0) {
      checkPass = false
      break
    }
  }
  const fn = () => {
    loading.value = true
    updateCdnNodeApi(data)
      .then(() => {
        Message.success('操作成功')
        getNodeInfo()
      })
      .finally(() => (loading.value = false))
  }
  if (!checkPass) {
    ModalHelper.confirm(
      {
        content: '节点 IP 与系统识别的不符，可能造成异常，确定要保存吗？',
      },
      fn,
    )
    return
  }
  fn()
}

function handleJump() {
  window.open('/cdn/node/group-management?type=open', '_target')
}

async function refreshGroupList() {
  await getClusterList()
  const groupExists = groupOptions.value.some(
    item => item.value === formState.group_id,
  )
  if (!groupExists) {
    formState.group_id = ''
    formState.group_type = undefined
  }

  Message.success('操作成功')
}

watch(
  () => route.params.id,
  (v) => {
    if (v) {
      getNodeInfo()
    }
  },
  {
    immediate: true,
  },
)
onMounted(() => {
  getClusterList()
})

function renderSelectedLabel(option) {
  const item = groupOptions.value.find(opt => opt.value === option.value)
  // return `${item.label} <span class="${item.type === 1 ? 'group-1' : 'group-2'}">${item.type === 1 ? '(组1)' : '(组2)'}</span>`
  // if (item) {
  //   return {
  //     html: `${item.label} <span class="ml-1 text-12px text-[#8F959E]">${item.type === 1 ? '(边缘组)' : '(上游组)'}</span>`,
  //   }
  // }
  // return ''
  // return h('div', { class: 'option-content' }, [
  //   h('span', {
  //     style: {
  //       float: 'left',
  //       marginRight: '8px'
  //     }
  //   }, item.label),
  //   h('span', {
  //     class: item.type === 1 ? 'group-1' : 'group-2',
  //   }, item.type === 1 ? '(边缘组)' : '(上游组)'
  // ]);
}

const selectedItem = computed(() => {
  return groupOptions.value.find(item => item.value === formState.group_id)
})

function groupTypeChange(item) {
  if (item) {
    formState.group_type = selectedItem.value?.type
  } else {
    formState.group_type = undefined
  }
}
</script>

<template>
  <main-container :show-pagination="false">
    <template #title>
      <a-breadcrumb class="main-container__breadcrumb">
        <a-breadcrumb-item>
          <router-link :to="{ name: 'CdnNodeNodeList' }">
            节点列表
          </router-link>
        </a-breadcrumb-item>
        <a-breadcrumb-item class="text-12px">
          {{ nodeName }}
        </a-breadcrumb-item>
      </a-breadcrumb>
    </template>
    <div class="mt-24px" />
    <div
      style="height: calc(100vh - 240px); overflow: auto"
      class="mt-2"
    >
      <div class="ml-2px h-full">
        <a-form
          ref="formRef"
          :model="formState"
          :rules="rules"
          layout="vertical"
          class="w-100!"
        >
          <a-form-item
            label="节点名称"
            field="name"
            asterisk-position="end"
          >
            <a-input
              v-model="formState.name"
              :max-length="32"
              show-word-limit
              placeholder="请输入节点名称"
            />
          </a-form-item>
          <a-form-item
            label="节点分组"
            field="group_id"
            asterisk-position="end"
          >
            <a-select
              v-model="formState.group_id"
              placeholder="请选择节点分组"
              show-footer-on-empty
              @change="groupTypeChange"
            >
              <template #label="data">
                <span>{{ data.data.label }}</span>
                <span class="ml-1 text-12px text-[#8F959E]">
                  {{ selectedItem?.type === 1 ? '(边缘组)' : '(上游组)' }}
                </span>
              </template>
              <a-option
                v-for="item in groupOptions"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              >
                <span style="float: left">{{ item.label }}</span>
                <span class="ml-1 text-12px text-[#8F959E]">{{
                  item.type === 1 ? '(边缘组)' : '(上游组)'
                }}</span>
              </a-option>
              <template #footer>
                <div
                  class="h-8 flex cursor-pointer items-center gap-x-1 px-3 text-[#00A65B] leading-8"
                  @click="handleJump"
                >
                  <span class="text-xs leading-[19px]">新建分组</span>
                  <i-icons-jump size="14px" />
                </div>
              </template>
            </a-select>
            <a-button
              class="ml-2 w-8"
              type="outline"
              @click="refreshGroupList"
            >
              <div class="w-8 flex items-center justify-center">
                <i-icons-refresh
                  size="14px"
                  class="h-14px! w-14px!"
                />
              </div>
            </a-button>
          </a-form-item>

          <a-form-item
            v-if="formState.group_type === 1"
            label="加入解析"
            field="enable_resolve"
            hide-asterisk
          >
            <template #label>
              <div class="flex items-center gap-x-1">
                <span>加入解析</span>
                <span class="text-[#FA5566]">*</span>
                <a-tooltip
                  :content-style="{ 'max-width': '509px' }"
                  :show-arrow="false"
                >
                  <i-icons-question class="question-icon text-#86909C" />
                  <template #content>
                    <span>
                      1.立即加入，该节点将参与链路解析。
                      <br>
                      2.暂不加入，该节点则不会参与链路解析。
                    </span>
                  </template>
                </a-tooltip>
              </div>
            </template>
            <div class="w-full">
              <div class="h-8">
                <a-radio-group
                  v-model="formState.enable_resolve"
                  class="ml-2"
                >
                  <a-radio :value="true">
                    立即加入
                  </a-radio>
                  <a-radio :value="false">
                    暂不加入
                  </a-radio>
                </a-radio-group>
              </div>
            </div>
          </a-form-item>

          <a-form-item
            field="ips"
            asterisk-position="end"
            class="level-item node-ip"
          >
            <template #label>
              <span>节点 IP <span class="text-[#FA5566]">*</span></span>
              <a-tooltip :show-arrow="false">
                <i-icons-question
                  class="question-icon text-sm text-[#86909C]"
                />
                <template #content>
                  <span>
                    1. 如果您的网卡为弹性网卡，可能会造成系统获取节点 IP
                    错误，请根据实际情况填写。
                  </span>
                  <br>
                  <span> 2. 请确保节点 IP 能在公网正常访问。</span>
                </template>
              </a-tooltip>
              <a-popover
                position="right"
                trigger="click"
                background-color="#fff"
                :arrow-style="{
                  'border-left': '1px solid #EEEFF2',
                  'border-bottom': '1px solid #EEEFF2',
                  'z-index': 100,
                  'display': 'none',
                }"
                :content-style="{
                  'border': '1px solid #F2F3F5',
                  'padding': '4px',
                  'box-shadow':
                    '0 4px 6px - 1px rgba(0, 0, 0, 0.10), 0 2px 4px - 2px',
                  'border-radius': '8px',
                  /* shadow-md */
                }"
              >
                <template #content>
                  <get-ip
                    v-model:ips="formState.ips"
                    :report-ips="formState?.report_ips"
                    @validate-ip="handleValidateIp"
                  />
                </template>
                <div class="node-ip-label">
                  <i-icons-cloud-download />
                  获取 IP
                </div>
              </a-popover>
            </template>
            <a-table
              :columns="tableColumn"
              :data="formState.ips"
              class="node-ip-table"
              :pagination="false"
            >
              <template #ip="{ record, rowIndex }">
                <a-form-item
                  :field="`ips[${rowIndex}].ip`"
                  hide-asterisk
                  hide-label
                  :rules="nodeIpRules"
                  validate-trigger="blur"
                >
                  <a-input
                    v-model="record.ip"
                    placeholder="请输入 IP"
                  />
                </a-form-item>
              </template>
              <template #action="{ rowIndex }">
                <a-link
                  v-if="rowIndex === 0"
                  :hoverable="false"
                  disabled
                >
                  当前为主 IP
                </a-link>
                <a-link
                  v-else
                  :hoverable="false"
                  @click="handleTableCommand('set_main', rowIndex)"
                >
                  设置为主 IP
                </a-link>
                <a-link
                  :hoverable="false"
                  status="danger"
                  :disabled="rowIndex === 0"
                  @click="handleTableCommand('delete', rowIndex)"
                >
                  <i-icons-delete size="16px" />
                </a-link>
              </template>
              <template #footer>
                <a-link
                  class="cloud-diverse-select h-[30px] w-fit items-center gap-x-2 !flex"
                  :hoverable="false"
                  :disabled="formState.ips.length > 9"
                  @click="handleTableCommand('add')"
                >
                  <i-icons-table-add />
                  添加节点 IP
                </a-link>
              </template>
            </a-table>
          </a-form-item>
        </a-form>
        <a-button
          type="primary"
          class="mt-6"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </a-button>
      </div>
    </div>
  </main-container>
</template>

<style lang="less" scoped>
.arco-form {
  .level-item :deep(.arco-form-item-label) {
    display: flex;
    align-items: center;
    column-gap: 4px;
  }

  .node-ip:deep(.arco-form-item-label) {
    width: 100%;

    .node-ip-label {
      @apply flex items-center gap-x-1 flex-1 text-primary order-2 justify-end cursor-pointer;
    }
  }
}

.node-ip-table {
  //border: 1px solid #dfe2e5;
  //@apply rounded-2 overflow-hidden;

  :deep(.arco-table-container) {
    border-radius: 8px 8px 0px 0px !important;
  }

  :deep(.arco-table-tr) {
    @apply !bg-#fff;
  }

  :deep(.arco-table-th) {
    @apply !bg-transparent;
  }

  :deep(.arco-table-footer) {
    //border-width: 0px !important;
    border-radius: 0px 0px 8px 8px !important;
    border: 1px solid #f0f5f5;
    border-top: none;
  }
}

.question-icon {
  color: #86909c;
  width: 14px !important;
  height: 14px !important;
  cursor: pointer;

  &:hover {
    color: #00a65b;
  }
}
</style>
